<?php

namespace App\Imports;

use App\Http\Common\Globals;
use App\Http\Common\MyUtils;
use App\Http\Controllers\Admin\managecenter\HouswholdsPrevController;
use App\Http\Controllers\Admin\managecenter\RoomsController;
use App\Http\Controllers\Admin\managecenter\UnitsController;
use App\Models\Front\RoomHouswhold;
use App\Models\HouswholdsPrev;
use App\Models\Rooms;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;
use Maatwebsite\Excel\Concerns\ToCollection;

class RoomsImport implements ToCollection
{
    // 请求
    public $request = "";
    public $wy_area_id = 1;//小区id
    public $type = 1;//类型
    public function __construct($wy_area_id,$request,$type)
    {
        $this->request =$request;
        $this->wy_area_id =$wy_area_id;
        $this->type =$type;
    }

    public function mapping1(): array
    {
        return [
            "bname"=>'楼宇名称',
            "uname"=>'单元号',
            "rname"=>'房号',
            "floor"=>'所在楼层',
            "build_space"=>'建筑面积',
            "inside_space"=>'套内面积',
            "public_space"=>'公摊面积',
            "type"=>'房屋类型',
            "toward"=>'房屋朝向',
            "finished_time"=>'交房时间',
            "property_year"=>'产权年限',
            "apartment_room"=>'室',
            "apartment_hall"=>'厅',
            "apartment_toilet"=>'卫',
            "remark"=>'备注',
        ];
    }

    public function mapping2(): array
    {
        return [
            "name"=>'预留住户',
            "identity"=>'预留住户身份',
            "phone"=>'预留住户手机号',
            "id_photo"=>'预留住户身份证号码',
        ];
    }

    /**
     * 普通情况下会自动运行3次，
     * @param Collection $rows
     * @return bool
     */
    public function collection(Collection $rows)
    {
        // 将exel的内容转换成适合的数组
        $res = MyUtils::exel2Array(array_filter($rows->all()));
        // 将exel的中文 键名 内容转换成字符串 键名 的数组，房间信息
        $resArray1 = array_values(MyUtils::exel2Array_($res,$this->mapping1()));
        // 预留信息
        $resArray2 = array_values(MyUtils::exel2Array_($res,$this->mapping2()));
        if ($resArray1 && $resArray2){
            Globals::$error="";
            foreach ($resArray1 as $k=>$item){
                DB::transaction(function () use($k,$resArray1,$resArray2){
                    // 拿到房间的控制器
                    $rooms = new RoomsController();
                    // 拿到住户预留的控制器
                    $houswholdsPrev = new HouswholdsPrevController();
                    // 拿到 单元 的控制器
                    $units = new UnitsController();
                    // 查询房间是否存在
                    $resArrayTemp1[$k]['wy_area_id'] = $this->wy_area_id;
                    $resArrayTemp1[$k]['rname'] = trim($resArray1[$k]['rname']);
                    $resArrayTemp1[$k]['uname'] = trim($resArray1[$k]['uname']);
                    $resArrayTemp1[$k]['bname'] = trim($resArray1[$k]['bname']);
                    $rooms->request->request->add($resArrayTemp1[$k]);
                    $rooms->request->request->remove("local_path");
                    Globals::$request = $rooms->request;
                    $rooms->model->importQuery($rooms->request);
                    $room = $rooms->model->one_();
                    // 查询单元是否存在，不存在就提示创建单元
                    // 查询哪个楼宇 哪个单元
                    $resArrayTemp2[$k]['wy_area_id'] = $this->wy_area_id;
                    $resArrayTemp2[$k]['uname'] = trim($resArray1[$k]['uname']);
                    $resArrayTemp2[$k]['bname'] = trim($resArray1[$k]['bname']);
                    $units->request->request->add($resArrayTemp2[$k]);
                    $units->request->request->remove("local_path");
                    $units->request->request->remove("type");
                    Globals::$request = $units->request;
                    $units->model->importQuery($units->request);
                    $unit = $units->model->one_();
                    if ($unit){// 单元存在 就将 rname替换成id
                        $rooms->request->request->set("wy_unit_id",$unit->id);
                        $rooms->request->request->set("wy_build_id",$unit->wy_build_id);
                        if (!$room){
                            // 移除name
                            $rooms_ =  new $rooms;
                            $rooms_->request->request->add($resArray1[$k]);
                            $rooms_->request->request->set("wy_unit_id",$unit->id);
                            $rooms_->request->request->set("wy_build_id",$unit->wy_build_id);
                            $rooms_->request->request->remove("local_path");
                            $rooms_->request->request->remove("rname");
                            $rooms_->request->request->remove("bname");
                            $rooms_->request->request->remove("uname");
                            $rooms_->request->request->set("name",trim($resArray1[$k]['rname']));
                            $rooms_->request->request->set("houswhold_pre",$resArray2[$k]);
                            $t = $rooms->model->store($rooms_->request);
                            $room = Rooms::where('id',$t)->first();
                        }
                        if ($room){// 如果房间存在了，就比对预留的户主
                            // 查询预留户主信息 是否存在
                            $resArray2[$k]['wy_area_id'] = $this->wy_area_id;
                            $houswholdsPrev->request->request->add(['wy_room_id'=>$room->id]);
                            $houswholdsPrev->request->request->remove("local_path");
                            $houswholdsPrev->request->request->remove("type");
                            Globals::$request = $houswholdsPrev->request;
                            $houswholdPrev = HouswholdsPrev::where($houswholdsPrev->request->request->all())->first();
                            // 移除name
                            $rooms->request->request->add($resArray1[$k]);
                            $rooms->request->request->remove("rname");
                            $rooms->request->request->remove("bname");
                            $rooms->request->request->remove("uname");
                            $rooms->request->request->set("name",$resArray1[$k]['rname']);
                            switch ($this->type){
                                case 1:// 重复数据不导入
                                    if (!$houswholdPrev){// 预留户主存在，就修改这条预留户主
                                        // 预留户主不存在，就新增预留户主
                                        $houswholdsPrev->request->request->set("project_id",MyUtils::getSessionConfig('PROJECT_ID'));
                                        $houswholdsPrev->request->request->remove('wy_room_id');
                                        $id = $houswholdsPrev->model->store($houswholdsPrev->request->request->all());
                                        // 新增完预留信息，就新增该住户身份
                                        $roomHouswholdData = [
                                            'wy_houswhold_id'=>$id,
                                            'wy_room_id'=>$room->id,
                                            'identity'=>$resArray2[$k]['identity']
                                        ];
                                        $roomHouswhold = RoomHouswhold::where($roomHouswholdData)->first();
                                        if (!$roomHouswhold){
                                            RoomHouswhold::insert($roomHouswholdData);
                                        }
                                    }
                                    break;
                                case 2:// 替换重复数据 不追加关联关系
                                    if (!$houswholdPrev){// 预留户主存在，就修改这条预留户主
                                        // 预留户主不存在，就新增预留户主
                                        $houswholdsPrev->request->request->set("project_id",MyUtils::getSessionConfig('PROJECT_ID'));
                                        $houswholdsPrev->request->request->remove('wy_room_id');
                                        $id = $houswholdsPrev->model->store($houswholdsPrev->request->request->all());
                                        // 新增完预留信息，就新增该住户身份
                                        $roomHouswholdData = [
                                            'wy_houswhold_id'=>$id,
                                            'wy_room_id'=>$room->id,
                                            'identity'=>$resArray2[$k]['identity']
                                        ];
                                        $roomHouswhold = RoomHouswhold::where($roomHouswholdData)->first();
                                        if (!$roomHouswhold){
                                            RoomHouswhold::insert($roomHouswholdData);
                                        }
                                    }
                                    Rooms::where("id",$room->id)->update($rooms->request->request->all());
                                    break;
                                case 3:// 替换重复数据 并追加关联关系
                                    if ($houswholdPrev){// 预留户主存在，就修改这条预留户主
                                        $houswholdsPrev->request->request->set("id",$houswholdPrev->id);
                                        $houswholdsPrev->request->request->add($resArray2[$k]);
                                        $houswholdsPrev->request->request->set("wy_room_id",$room->id);// 追加 房间绑定预留信息
                                        $houswholdsPrev->model->storeUpdate($houswholdsPrev->request->request->all());
                                        // 新增完预留信息，就新增该住户身份
                                        $roomHouswholdData = [
                                            'wy_houswhold_id'=>$houswholdPrev->id,
                                            'wy_room_id'=>$room->id,
                                            'identity'=>$resArray2[$k]['identity']
                                        ];
                                        $roomHouswhold = RoomHouswhold::where($roomHouswholdData)->first();
                                        if (!$roomHouswhold){
                                            RoomHouswhold::insert($roomHouswholdData);
                                        }
                                    }else{// 预留户主不存在，就新增预留户主
                                        $houswholdsPrev->request->request->add($resArray2[$k]);
                                        $houswholdsPrev->request->request->set("project_id",MyUtils::getSessionConfig('PROJECT_ID'));
                                        $houswholdsPrev->request->request->set("wy_room_id",$room->id);
                                        $id = $houswholdsPrev->model->store($houswholdsPrev->request->request->all());
                                        // 新增完预留信息，就新增该住户身份
                                        $roomHouswholdData = [
                                            'wy_houswhold_id'=>$id,
                                            'wy_room_id'=>$room->id,
                                            'identity'=>$resArray2[$k]['identity']
                                        ];
                                        $roomHouswhold = RoomHouswhold::where($roomHouswholdData)->first();
                                        if (!$roomHouswhold){
                                            RoomHouswhold::insert($roomHouswholdData);
                                        }
                                    }
                                    Rooms::where("id",$room->id)->update($rooms->request->request->all());
                                    break;
                            }
                        }
                        return true;
                    }else{// 单元不存在，就不操作
                        $k++;
                        Globals::$error .= "第 $k 条“单元或者楼宇”不存在；";
                        return false;
                    }
                });
            }
            return true;
        }else{
            return false;
        }
    }


}
